<!-- 人员管理 -->
<!-- art-full-height 自动计算出页面剩余高度 -->
<!-- art-table-card 一个符合系统样式的 class，同时自动撑满剩余高度 -->
<!-- 更多 useTable 使用示例请移步至 功能示例 下面的 高级表格示例 -->
<template>
  <div class="user-page art-full-height">
    <!-- 搜索栏 -->
    <UserSearch v-model="searchForm" @search="handleSearch" @reset="handleReset"></UserSearch>

    <ElCard class="art-table-card" shadow="never">
      <!-- 表格头部 -->
      <ArtTableHeader v-model:columns="columnChecks" :loading="loading" @refresh="refreshData">
        <template #left>
          <ElSpace wrap>
            <ElButton @click="showDialog('add')" v-ripple>新增人员</ElButton>
          </ElSpace>
        </template>
      </ArtTableHeader>

      <!-- 表格 -->
      <ArtTable
        :loading="loading"
        :data="data"
        :columns="columns"
        :pagination="pagination"
        @selection-change="handleSelectionChange"
        @pagination:size-change="handleSizeChange"
        @pagination:current-change="handleCurrentChange"
      >
      </ArtTable>

      <!-- 用户弹窗 -->
      <UserDialog
        v-model:visible="dialogVisible"
        :type="dialogType"
        :user-data="currentUserData"
        @submit="handleDialogSubmit"
      />
    </ElCard>
  </div>
</template>

<script setup lang="ts">
  import ArtButtonTable from '@/components/core/forms/art-button-table/index.vue'
  import { ACCOUNT_TABLE_DATA } from '@/mock/temp/formData'
  import { ElMessageBox, ElMessage, ElTag, ElImage } from 'element-plus'
  import { useTable } from '@/composables/useTable'
  import UserSearch from './modules/user-search.vue'
  import UserDialog from './modules/user-dialog.vue'
  import { apiEmployeeGetPageUsingPost } from '@/api'

  defineOptions({ name: 'User' })

  type UserListItem = Api.SystemManage.UserListItem

  // 弹窗相关
  const dialogType = ref<Form.DialogType>('add')
  const dialogVisible = ref(false)
  const currentUserData = ref<Partial<UserListItem>>({})

  // 选中行
  const selectedRows = ref<UserListItem[]>([])

  // 搜索表单
  const searchForm = ref({
    employeeGender: undefined,
    employeeName: undefined,
    tagId: undefined,
    positionId: undefined,
  })

  // 用户状态配置
  const USER_STATUS_CONFIG = {
    '1': { type: 'success' as const, text: '在线' },
    '2': { type: 'info' as const, text: '离线' },
    '3': { type: 'warning' as const, text: '异常' },
    '4': { type: 'danger' as const, text: '注销' }
  } as const

  /**
   * 获取用户状态配置
   */
  const getUserStatusConfig = (status: string) => {
    return (
      USER_STATUS_CONFIG[status as keyof typeof USER_STATUS_CONFIG] || {
        type: 'info' as const,
        text: '未知'
      }
    )
  }

  const {
    columns,
    columnChecks,
    data,
    loading,
    pagination,
    getData,
    searchParams,
    resetSearchParams,
    handleSizeChange,
    handleCurrentChange,
    refreshData
  } = useTable({
    // 核心配置
    core: {
      apiFn: apiEmployeeGetPageUsingPost,
      apiParams: {
        body: {
          // employeeGender:searchForm.value.employeeGender,
          // loginName:searchForm.value.loginName
        }
      },
      paginationWrapper: 'body', // 将分页参数包装到 body 对象中
      columnsFactory: () => [
        // { type: 'selection' }, // 勾选列
        { type: 'index', width: 60, label: '序号' }, // 序号
        {
          prop: 'loginName',
          label: '登录账号',
        },
        {
          prop: 'employeeName',
          label: '姓名',
          width: 280,
          // formatter: (row) => {
          //   return h('div', { class: 'user', style: 'display: flex; align-items: center' }, [
          //     h(ElImage, {
          //       class: 'avatar',
          //       src: row.avatar,
          //       previewSrcList: [row.avatar],
          //       // 图片预览是否插入至 body 元素上，用于解决表格内部图片预览样式异常
          //       previewTeleported: true
          //     }),
          //     h('div', {}, [
          //       h('p', { class: 'user-name' }, row.userName),
          //       h('p', { class: 'email' }, row.userEmail)
          //     ])
          //   ])
          // }
        },
        {
          prop: 'employeeGender',
          label: '性别',
          sortable: true,
          // checked: false, // 隐藏列
          formatter: (row) => row.employeeGender ==1 ?'男':'女'
        },
        { prop: 'employeePhone', label: '手机号' },
        {
          prop: 'deptName',
          label: '部门',
          formatter: (row) => row.deptIdVo?.deptName || ''
        },
        {
          prop: 'positionName',
          label: '职务',
          formatter: (row) => row.positionIdVo?.positionName || ''
        },
        {
          prop: 'tags',
          label: '个人标签',
          formatter: (row) => {
            if (!row.tagList || !Array.isArray(row.tagList) || row.tagList.length === 0) {
              return '-'
            }
            
            // 显示标签列表，最多显示3个，超出部分显示...
            const tags = row.tagList.slice(0, 3).map(tag => tag.tagName || '').join(', ')
            const more = row.tagList.length > 3 ? '...' : ''
            return tags + more
          }
        },
         {
          prop: 'disabledFlag',
          label: '人员状态',
          formatter: (row) => {
            const status = row.disabledFlag === 1 ? '禁用' : '启用'
            const type = row.disabledFlag === 1 ? 'danger' : 'success'
            return h(ElTag, { type }, () => status)
          }
        },
         {
          prop: 'createTime',
          label: '创建日期',
          sortable: true,
          formatter: (row) => {
            if (!row.createTime) return '-'
            
            try {
              // 获取时间戳字符串
              const timestampStr = String(row.createTime)
              
              // 检查是否为14位数字
              if (timestampStr.length === 14 && /^\d{14}$/.test(timestampStr)) {
                // 解析14位时间戳：YYYYMMDDHHmmss
                const year = parseInt(timestampStr.substring(0, 4))
                const month = parseInt(timestampStr.substring(4, 6)) - 1 // JavaScript月份从0开始
                const day = parseInt(timestampStr.substring(6, 8))
                const hours = parseInt(timestampStr.substring(8, 10))
                const minutes = parseInt(timestampStr.substring(10, 12))
                const seconds = parseInt(timestampStr.substring(12, 14))
                
                // 创建日期对象
                const date = new Date(year, month, day, hours, minutes, seconds)
                
                // 检查日期有效性
                if (isNaN(date.getTime())) {
                  return row.createTime
                }
                
                // 手动补零的函数
                const formatNumber = (num) => {
                  return num < 10 ? '0' + num : num
                }
                
                // 返回格式化后的日期字符串
                return `${year}-${formatNumber(month + 1)}-${formatNumber(day)} ${formatNumber(hours)}:${formatNumber(minutes)}:${formatNumber(seconds)}`
              } else {
                // 如果不是14位时间戳，尝试作为毫秒时间戳处理
                let timestamp = row.createTime
                
                // 如果是13位数字，可能是毫秒时间戳
                if (String(timestamp).length === 13) {
                  timestamp = timestamp * 1000
                }
                
                const date = new Date(timestamp)
                
                // 检查日期有效性
                if (isNaN(date.getTime())) {
                  return row.createTime
                }
                
                // 手动补零的函数
                const formatNumber = (num) => {
                  return num < 10 ? '0' + num : num
                }
                
                // 获取年月日时分秒
                const year = date.getFullYear()
                const month = date.getMonth() + 1
                const day = date.getDate()
                const hours = date.getHours()
                const minutes = date.getMinutes()
                const seconds = date.getSeconds()
                
                // 返回格式化后的日期字符串
                return `${year}-${formatNumber(month)}-${formatNumber(day)} ${formatNumber(hours)}:${formatNumber(minutes)}:${formatNumber(seconds)}`
              }
            } catch (error) {
              // 出现任何错误都返回原始值
              return row.createTime
            }
          }
        },
        {
          prop: 'operation',
          label: '操作',
          width: 120,
          fixed: 'right', // 固定列
          formatter: (row) =>
            h('div', [
              h(ArtButtonTable, {
                type: 'edit',
                onClick: () => showDialog('edit', row)
              }),
              // h(ArtButtonTable, {
              //   type: 'delete',
              //   onClick: () => deleteUser(row)
              // })
            ])
        }
      ]
    },
    // 数据处理
    transform: {
      // 数据转换器 - 替换头像
      dataTransformer: (records: any) => {
        // 类型守卫检查
        if (!Array.isArray(records)) {
          console.warn('数据转换器: 期望数组类型，实际收到:', typeof records)
          return []
        }

        // 使用本地头像替换接口返回的头像
        return records.map((item: any, index: number) => {
          return {
            ...item,
            avatar: ACCOUNT_TABLE_DATA[index % ACCOUNT_TABLE_DATA.length].avatar
          }
        })
      }
    }
  })

   /**
   * 搜索处理
   * @param params 参数
   */
  const handleSearch = (params: Record<string, any>) => {
    // 处理日期区间参数，把 daterange 转换为 startTime 和 endTime
    // const { daterange, ...filtersParams } = params
    // const [startTime, endTime] = Array.isArray(daterange) ? daterange : [null, null]
    searchForm.value.employeeGender = params.employeeGender
    searchForm.value.employeeName = params.employeeName
    searchForm.value.tagId = params.tagId
    searchForm.value.positionId = params.positionId
    searchForm.value.disabledFlag = params.disabledFlag
    searchParams.body.employeeGender = searchForm.value.employeeGender
    searchParams.body.employeeName = searchForm.value.employeeName
    searchParams.body.tagId = searchForm.value.tagId
    searchParams.body.positionId = searchForm.value.positionId
    searchParams.body.disabledFlag = searchForm.value.disabledFlag
    // 搜索参数赋值
    // Object.assign(searchParams, { ...filtersParams, startTime, endTime })
    getData()
  }

  /**
   * 重置搜索条件
   */
  const handleReset = () => {
    // 清除所有搜索条件
    searchForm.value.employeeGender = undefined
    searchForm.value.employeeName = undefined
    searchForm.value.tagId = undefined
    searchForm.value.positionId = undefined
    searchForm.value.disabledFlag = undefined
    
    // 清除API参数中的搜索条件
    searchParams.body.employeeGender = undefined
    searchParams.body.employeeName = undefined
    searchParams.body.tagId = undefined
    searchParams.body.positionId = undefined
    searchParams.body.disabledFlag = undefined
    
    // 重新加载数据
    getData()
  }

  /**
   * 显示用户弹窗
   */
  const showDialog = (type: Form.DialogType, row?: UserListItem): void => {
    console.log('打开弹窗:', { type, row })
    dialogType.value = type
    currentUserData.value = row || {}
    nextTick(() => {
      dialogVisible.value = true
    })
  }

  /**
   * 删除用户
   */
  const deleteUser = (row: UserListItem): void => {
    console.log('删除用户:', row)
    ElMessageBox.confirm(`确定要注销该用户吗？`, '注销用户', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error'
    }).then(() => {
      ElMessage.success('注销成功')
    })
  }

  /**
   * 处理弹窗提交事件
   */
  const handleDialogSubmit = async () => {
    try { 
      dialogVisible.value = false
      currentUserData.value = {}
      // 刷新数据列表
      refreshData()
    } catch (error) {
      console.error('提交失败:', error)
      ElMessage.error('提交失败，请重试')
    }
  }

  /**
   * 处理表格行选择变化
   */
  const handleSelectionChange = (selection: UserListItem[]): void => {
    selectedRows.value = selection
    console.log('选中行数据:', selectedRows.value)
  }
</script>

<style lang="scss" scoped>
  .user-page {
    :deep(.user) {
      .avatar {
        width: 40px;
        height: 40px;
        margin-left: 0;
        border-radius: 6px;
      }

      > div {
        margin-left: 10px;

        .user-name {
          font-weight: 500;
          color: var(--art-text-gray-800);
        }
      }
    }
  }
</style>
